package com.urea.web.controller.urea;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.urea.common.core.domain.entity.Customer;
import com.urea.common.exception.ServiceException;
import com.urea.common.utils.StringUtils;
import com.urea.common.utils.file.FileUtils;
import com.urea.system.domain.FileInfo;
import com.urea.system.domain.vo.CustomerStatisticsVo;
import com.urea.system.domain.vo.CustomerVo;
import com.urea.system.domain.vo.OrderDto;
import com.urea.system.service.IFileInfoService;
import com.urea.system.service.IOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.urea.common.annotation.Log;
import com.urea.common.core.controller.BaseController;
import com.urea.common.core.domain.AjaxResult;
import com.urea.common.enums.BusinessType;
import com.urea.system.service.ICustomerService;
import com.urea.common.utils.poi.ExcelUtil;
import com.urea.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户信息Controller
 * 
 * @author liuzd
 * @date 2023-08-01
 */
@RestController
@RequestMapping("/customer")
@Api(tags = "小程序用户相关")
public class CustomerController extends BaseController
{
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IFileInfoService fileInfoService;
    @Value("${ruoyi.profile}")
    private String basePath;
    @Value("${localhost.url}")
    private String url;

    /**
     * pc用户统计列表
     */
//    @PreAuthorize("@ss.hasPermi('customer:list')")
    @GetMapping("/statisticsList")
    @ApiOperation("pc用户统计列表")
    public TableDataInfo statisticsList(CustomerVo customer)
    {
        startPage();
        List<CustomerStatisticsVo> list = customerService.statisticsList(customer);
        return getDataTable(list);
    }

    /**
     * pc用户统计数据
     * @param customer 过滤条件
     * @return 结果
     */
    @GetMapping("/statistics")
    @ApiOperation("pc用户统计数据")
    public AjaxResult statistics(CustomerVo customer)
    {
        return success(customerService.statistics(customer));
    }

    /**
     * pc用户统计列表导出
     */
    @Log(title = "pc用户统计列表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/statisticsListExport")
    @ApiOperation("pc用户统计列表导出")
    public void export(HttpServletResponse response, CustomerVo customer)
    {
        List<CustomerStatisticsVo> list = customerService.statisticsList(customer);
        ExcelUtil<CustomerStatisticsVo> util = new ExcelUtil<CustomerStatisticsVo>(CustomerStatisticsVo.class);
        util.exportExcel(response, list, "用户统计数据");
    }

    /**
     * 导出客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('customer:export')")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Customer customer)
    {
        List<Customer> list = customerService.selectCustomerList(customer);
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        util.exportExcel(response, list, "客户信息数据");
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('customer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(customerService.selectCustomerById(id));
    }

    /**
     * 根据手机号获取客户信息详细信息
     */
    @GetMapping(value = "/phone/{phone}")
    @ApiOperation("根据手机号获取客户信息详细信息")
    public AjaxResult getInfoByPhone(@PathVariable("phone") Long phone)
    {
        return success(customerService.getInfoByPhone(phone));
    }


    /**
     * 新增客户信息
     */
    @PreAuthorize("@ss.hasPermi('customer:add')")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Customer customer)
    {
        return toAjax(customerService.insertCustomer(customer));
    }

    /**
     * 修改客户信息
     */
    @PreAuthorize("@ss.hasPermi('customer:edit')")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Customer customer)
    {
        return toAjax(customerService.updateCustomer(customer));
    }

    /**
     * 删除客户信息
     */
    @PreAuthorize("@ss.hasPermi('customer:remove')")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(customerService.deleteCustomerByIds(ids));
    }


    /**
     * 上传文件
     */
    @PostMapping("/headImgUpload")
    @ApiOperation("头像上传")
    public AjaxResult headImgUpload(@RequestParam("file") MultipartFile file,
                                    @ApiParam(name = "phone",value = "用户手机号")@RequestParam("phone")String phone)  {
        // 获取文件目录
        String yyyyMMdd = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = IdUtil.fastSimpleUUID();
        String originalFilename = file.getOriginalFilename();
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setSize(file.getSize());
        fileInfo.setType("1");
        if (StringUtils.isNotBlank(originalFilename)){
            String name = FileUtils.getName(originalFilename);
            String ext = name.substring(name.lastIndexOf("."));
            fileName = fileName.concat(".").concat(ext);
            fileInfo.setExt(ext);
        }
        String s = basePath + "/" +yyyyMMdd+"/"+ fileName;
        fileInfo.setPath(s);
        fileInfoService.save(fileInfo);
        File file1 = new File(s);
        try {
            FileUtil.writeFromStream(file.getInputStream(),file1);
            Customer one = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getPhone, phone));
            Customer customer = new Customer();
            if (Objects.isNull(one)){
                throw new ServiceException("用户信息有误");
            }
            customer.setId(one.getId());
            customer.setHeadImgUrl(url.concat("fileInfo/download/".concat(String.valueOf(fileInfo.getId()))));
            customerService.updateById(customer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @PostMapping("/headImgDownload")
    @ApiOperation("头像下载")
    public void headImgDownload(HttpServletResponse response,
                                @ApiParam(name = "customerVo",value = "用户手机号") @RequestBody CustomerVo customerVo)  {
        // 获取文件目录
        try {
            Customer one = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getPhone, customerVo.getPhone()));
            if (Objects.isNull(one)){
                throw new ServiceException("用户信息有误");
            }
            String headImgUrl = one.getHeadImgUrl();
            FileUtils.setAttachmentResponseHeader(response,"头像.png");
            FileUtil.writeToStream(new File(headImgUrl),response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/queryList")
    @ApiOperation("pc用户管理列表")
    public TableDataInfo queryList(CustomerVo vo){
        startPage();
        List<CustomerVo> list = customerService.queryList(vo);
        return getDataTable(list);
    }


    @GetMapping("/queryOrderListByUid")
    @ApiOperation("pc用户管理订单详情")
    public TableDataInfo queryList(Long userId){
        startPage();
        OrderDto dto = new OrderDto();
        dto.setCustomerId(userId);
        List<OrderDto> list = orderService.queryOrderList(dto);
        return getDataTable(list);
    }
}
